package util;

import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Utility class used for Hibernate sessionFactory building
 * 
 * @author 264524
 */
public class HibernateUtil {

	// Degbug & logging
	private static final Logger LOGGER = Logger.getLogger(HibernateUtil.class);

	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;

	private static final SessionFactory sessionFactory = buildSessionFactory();

	// database connection information
	private static final String jdbcDriver = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/bddenseirb";
	private static final String username = "root";
	private static final String password = "root";
	private static final String schema = "bddenseirb";
	private static final String dialect = "org.hibernate.dialect.MySQLDialect";
	private static final String hbm2ddlstrategy = "none"; // create, update,
															// drop-create, none
															// //
															// none,update,create-update

	/**
	 * Builds {@link SessionFactory} with specific configuration
	 * 
	 * @return {@link SessionFactory}
	 */
	private static SessionFactory buildSessionFactory() {

		try {

			// We add the annoted class to the configuration
			Configuration configuration = new Configuration();

			// Connection settings
			Properties properties = new Properties();
			properties.put("hibernate.show_sql", "true");
			properties.put("hibernate.connection.driver_class", jdbcDriver);
			properties.put("hibernate.connection.url", url);
			properties.put("hibernate.connection.username", username);
			properties.put("hibernate.connection.password", password);
			properties.put("hibernate.default_schema", schema);

			// SQL dialect
			properties.put("hibernate.dialect", dialect);

			properties.put("hibernate.hbm2ddl.auto", hbm2ddlstrategy);

			configuration.setProperties(properties);

			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();

			factory = configuration.buildSessionFactory(serviceRegistry);

			LOGGER.info("Loading Hibernate Session Factory with configurations");

		} catch (Throwable ex) {

			System.err
					.println("Failed to create sessionFactory object : " + ex);
			throw new ExceptionInInitializerError(ex);

		}

		return factory;
	}

	/**
	 * Returns {@link SessionFactory} instance
	 * 
	 * @return {@link SessionFactory}
	 */
	public static SessionFactory getSessionFactory() {

		return sessionFactory;
	}
}
